package com.itheima.filter;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class WemediaLoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获得请求对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //放行不需要登录就可以访问的路径
        String path = request.getURI().getPath();
        log.debug("请求的地址：{}", path);
        if (path.startsWith("/wemedia/login")) {
            return chain.filter(exchange);
        }
        //获得请求头中的token
        String token = request.getHeaders().getFirst("token");
        //如果有token（记得非空判断）
        if (StringUtils.isNotEmpty(token)) {

            //就检验token的有效性

            try {
                //如果有效就放行
                Claims claims = AppJwtUtil.getClaimsBody(token);
                if ( null !=  claims) {
                    //获得用户id
                    Long id = claims.get("id", Long.class);
                    //将用户id存储到请求头中，便于后面调用微服务上传素材时区别是哪个用户的
                    request.mutate().header(SystemConstants.USER_HEADER_NAME, id.toString());
                    //放行
                    return chain.filter(exchange);
                }

            } catch (ExpiredJwtException ex) {
                log.error("token已过期：" + ex);
            } catch (Exception e) {
                log.error("无效的token：" + e);
            }

        }
        //如果都没有放行，就返回401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //结束
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
